package com.dev.receiver;

import com.dev.utils.LogUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.window.dialog.ToastDialog;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventSubscribeInfo;
import ohos.event.commonevent.CommonEventSubscriber;

/**
 * 监听电量变化的订阅公告事件类
 */
public class BatterySubscriber extends CommonEventSubscriber {

    private AbilitySlice slice;
    public static final String COMMON_EVENT_BATTERY_CHANGED = "usual.event.BATTERY_CHANGED";
    public static final String COMMON_EVENT_BATTERY_LOW = "usual.event.BATTERY_LOW";
    public static final String COMMON_EVENT_BATTERY_OKAY = "usual.event.BATTERY_OKAY";

    public BatterySubscriber(CommonEventSubscribeInfo subscribeInfo, AbilitySlice slice) {
        super(subscribeInfo);
        this.slice = slice;
    }

    @Override
    public void onReceiveEvent(CommonEventData commonEventData) {
        int tagChange = 0;
        int tagLow = 0;
        int tagOk = 0;
        if (commonEventData == null || commonEventData.getIntent() == null) {
            return;
        }
        if (COMMON_EVENT_BATTERY_CHANGED.equals(commonEventData.getIntent().getAction())) {
            if(tagChange == 0){
                new ToastDialog(slice).setText("电池电量改变！").show();
                LogUtils.info("BATTERY", "battery is changed!");
            }
            tagChange++;
        } else if (COMMON_EVENT_BATTERY_LOW.equals(commonEventData.getIntent().getAction())) {
            if(tagLow == 0){
                new ToastDialog(slice).setText("电池电量过低！").show();
                LogUtils.info("BATTERY", "battery is low!");
            }
           tagLow++;
        } else if (COMMON_EVENT_BATTERY_OKAY.equals(commonEventData.getIntent().getAction())) {
            if(tagOk == 0){
                new ToastDialog(slice).setText("电池电量正常！").show();
                LogUtils.info("BATTERY", "battery is okay!");
            }
           tagOk++;
        }
    }
}
